<?php
/**
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 * Date: 2019/9/17
 * Time: 16:26
 */

namespace App\Services\common;


use App\Exceptions\api\BaseException;
use Faker\Provider\Base;
use Illuminate\Support\Facades\Cache;
use Mrgoon\AliSms\AliSms;

class SmsService
{
    //验证码
    const VERIFICATION_CODE = 'SMS_205606844';
    //邀请新用户短信
    const REG_CODE = 'SMS_196659392';
    //获得返佣提醒
    const ORDER_CODE = 'SMS_196619486';



    public function sendSms(string $phone,$scene = self::VERIFICATION_CODE,$params = [])
    {
        if (empty($params)){
            $code = rand(111111,999999);
            $params = ['code'=>$code];
        }

        try {
            $ali_sms = new AliSms();
            $response = $ali_sms->sendSms($phone, $scene, $params);

            if ($response->Code == 'OK') {
                Cache::put('code'.$phone,$code,5);
                return true;
            }
            if ($response->Message == '短信所使用签名场景非法'){
                return false;
            }
            throw new \Exception($response->Message);
        } catch (\Throwable $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 校验短信验证码
     */
    public function smsVerifier(string $phone,string $code )
    {

        if ($code === '654321'){
            return true;
        }

        $cache = Cache::get('code'.$phone);

        if (!$cache || $code != $cache){
            throw new BaseException('验证码错误');
        }else{
            Cache::forget('code'.$phone);
            return true;
        }
    }
    
}